/**
 * 设备保养详情
 * author Forjune
 */
import React, { useEffect, useState } from 'react'
import ProjectDes from 'components/common/projectDes'
import FoldTable from 'components/common/foldTable'
import DeviceMessage from 'components/common/deviceMessage'
import MaintenanceMessage from 'components/common/maintenanceMessage'
import TitleLine from 'components/common/titleLine'
import CheckPanel from 'components/common/checkPanel'
import PlanBasicMessage from 'components/common/planBasicMessage'
import { getTaskList, getUpkeepDetail, operTask } from 'service/actions/deviceUpkeep'
import deviceUpkeep from 'columns/deviceUpkeep'
import { connect } from 'dva'
import './index.styl'
import { message } from 'antd'

function Detail({ dispatch, location: { query: { id } }, process: { list } }) {
  // 任务执行状态
  deviceUpkeep.projectList[deviceUpkeep.projectList.length - 2].render = (text, record) => {
    if (record.failReason && text !== '—' && text === '成功') {
      return text + '：' + record.failReason
    } else {
      return text
    }
  }

  deviceUpkeep.projectList[deviceUpkeep.projectList.length - 1].render = (text, record) => {
    return (
      record.statusName === '待确认' && record.deleted !== 'Y' ?
        <>
          <span style={{ marginRight: '0.16rem', cursor: 'pointer' }} onClick={() => handleTask(record, 4)} className='btnStyl'>确认完成</span>
          <span style={{ cursor: 'pointer' }} onClick={() => handleTask(record, 5)} className='btnStyl'>不合格</span>
        </>
        :
        '—'
    )
  }

  const [planBasic, setPlanBasic] = useState({
    name: '',
    typeName: '',
    levelName: '',
    createdBy: '',
    createdTime: '',
    remark: ''
  })
  const [deviceMes, setDeviceMes] = useState({})
  const [maintenanceMes, setMaintenanceMes] = useState({})
  const [project, setProject] = useState([])
  const [procInsId, setProcInsId] = useState('')
  const [statusName, setStatusName] = useState()
  useEffect(() => {
    async function fetchData() {
      const data = await getUpkeepDetail({
        id,
        method: 'GET'
      })
      if (data && data.code === '000000') {
        const DATA = data.data
        dispatch({
          type: 'process/getList',
          payload: { id: DATA.procInsId },
        });
        setProcInsId(DATA.procInsId)
        setPlanBasic({
          name: DATA.name,
          typeName: DATA.typeName,
          levelName: DATA.levelName,
          createdBy: DATA.createdBy,
          createdTime: DATA.createdTime,
          remark: DATA.remark
        })
        setStatusName(DATA.statusName)
        setDeviceMes({
          ...DATA.deviceVo
        })
        setMaintenanceMes({
          ...DATA.maintainUserInfoVo
        })
        setProject([
          ...DATA.maintainTaskVoList.map(item => {
            return {
              ...item,
              current: 1
            }
          })
        ])
      }
      if (data && (data.code === '030200' || data.code === '050000')) {
        message.error(data.mesg+'222')
        // 返回列表页
      }
    }
    fetchData()
  }, [dispatch, id])

  // 更新节点流程
  const getListAgain = () => {
    dispatch({
      type: 'process/getList',
      payload: { id: procInsId },
    });
  }

  // 项目任务列表的分页
  async function handleChangePage(current, maintainTaskId) {
    const data = await getTaskList({
      current,
      maintainTaskId,
      size: 5
    })
    if (data && data.code === '000000') {
      let arr = project.map(item => {
        if (item.id === maintainTaskId) {
          item.maintainTaskCaseVos = data.data
          item.current = current
        }
        return item
      })
      setProject([...arr])
    }
  }

  // 项目列表里的操作按钮的执行事件
  async function handleTask(record, status) {
    const da = await operTask({
      id: record.id,
      status
    })
    if (da && da.code === '000000') {
      message.success(da.mesg, 2, async () => {
        const data = await getTaskList({
          current: record.current,
          maintainTaskId: record.maintainTaskId,
          size: 5
        })
        if (data && data.code === '000000') {
          let arr = project.map(item => {
            if (item.id === record.maintainTaskId) {
              item.maintainTaskCaseVos = data.data
            }
            return item
          })
          setProject([...arr])
        }
      })
    }
  }
  console.log('project', project)
  return (
    <div className="deviceUpkeep_detail">
      <div className="deviceUpkeep_detail-left">
        <PlanBasicMessage basicInfo={planBasic} />
        <div className="left-body">
          <div className="body-device">
            <DeviceMessage show={false} deviceInfo={deviceMes} title="设备信息" isDetail={true}/>
          </div>
          <div className="body-maintenance">
            <MaintenanceMessage show={false} title="保养员信息" maintenanceInfo={maintenanceMes} />
          </div>
        </div>
        <TitleLine title="保养项目信息" />
        <div className="left-table">
          {
            project.length > 0 && project.map(item => {
              return (
                <div style={{ marginBottom: '0.24rem' }} key={item.id}>
                  <div className="table-title">
                    <ProjectDes
                      projectInfo={
                        {
                          taskName: item.taskName,
                          cycle: item.cycle,
                          cycleType: item.cycleType,
                          startTime: item.startTime,
                          remark: item.remark
                        }
                      }
                    />
                    {
                      item.deleted === 'Y' && statusName !== '草稿' ?
                        <span className="table-title-tip table-title-tip_gray">
                          已删除
                          </span>
                        :
                        null
                    }
                    {
                      item.deleted === 'N' && item.maintainTaskCaseVos.records.some(it => it.statusName === '待确认') ?
                        <span className="table-title-tip">
                          待确认任务
                          </span>
                        :
                        null
                    }
                  </div>
                  <div className="table-body">
                    <FoldTable
                      tableInfo={item.maintainTaskCaseVos}
                      tableColumns={deviceUpkeep.projectList}
                      handleChangePage={(page) => handleChangePage(page, item.id)}
                    />
                  </div>
                </div>
              )
            })
          }
        </div>
      </div>
      <div className="deviceUpkeep_detail-right">
        <CheckPanel
          list={list && list.slice(1, list.length)}
          id={id}
          procInsId={procInsId}
          processType={'maintain'}
          getListAgain={getListAgain}
        />
      </div>
    </div>
  )
}

export default connect(({ process }) => ({
  process
}))(Detail);
